#-*- coding:utf-8 -*-
import MySQLdb,settings,codecs,os,sys,datetime,time,random,requests,hashlib,urllib,urllib2,md5,simplejson
from django.shortcuts import render_to_response
from django.http import HttpResponse,HttpResponseRedirect,HttpResponseForbidden,HttpResponseNotFound,HttpResponsePermanentRedirect
from datetime import timedelta, date 
from dict2xml import dict2xml
from django.core.cache import cache
from zz91db_dibang import dibangdb
from zz91tools import formattime,int_to_strall
import json,StringIO,Image,ImageDraw,ImageFont,ImageFilter,base64
from settings import pyuploadpath,pyimgurl

from xml.etree import ElementTree as ET
try:
    import cPickle as pickle
except ImportError:
    import pickle
from math import ceil
from wechat import weixintixin

db=dibangdb(1)
from zz91page import *
reload(sys) 
sys.setdefaultencoding('utf-8') 
nowpath=os.path.dirname(__file__)
execfile(nowpath+"/func/ermtools.py")
#更新
def api_updatelist(request):
    list=[]
    
    a="AudioRender.dll"
    list.append(a)
    a="HCCore.dll"
    list.append(a)
    a="HCNetSDK.dll"
    list.append(a)
    a="HWDecode.dll"
    list.append(a)
    a="MP_Render.dll"
    list.append(a)
    a="MP_VIE.dll"
    list.append(a)
    a="OUR_MIFARE.dll"
    list.append(a)
    a="PlayCtrl.dll"
    list.append(a)
    a="SuperRender.dll"
    list.append(a)
    a="YUVProcess.dll"
    list.append(a)
    a="erm.mdb"
    list.append(a)
    a="erm.exe"
    list.append(a)
    a="/pic/nopic.png"
    list.append(a)
    a="/HCNetSDKCom/SystemTransform.dll"
    list.append(a)
    a="/HCNetSDKCom/StreamTransClient.dll"
    list.append(a)
    a="/HCNetSDKCom/OpenAL32.dll"
    list.append(a)
    a="/HCNetSDKCom/msvcr90.dll"
    list.append(a)
    a="/HCNetSDKCom/libiconv2.dll"
    list.append(a)
    a="/HCNetSDKCom/HCVoiceTalk.dll"
    list.append(a)
    a="/HCNetSDKCom/HCPreview.dll"
    list.append(a)
    a="/HCNetSDKCom/HCPlayBack.dll"
    list.append(a)
    a="/HCNetSDKCom/HCIndustry.dll"
    list.append(a)
    a="/HCNetSDKCom/HCGeneralCfgMgr.dll"
    list.append(a)
    a="/HCNetSDKCom/HCDisplay.dll"
    list.append(a)
    a="/HCNetSDKCom/HCCoreDevCfg.dll"
    list.append(a)
    a="/HCNetSDKCom/HCAlarm.dll"
    list.append(a)
    a="/HCNetSDKCom/AudioIntercom.dll"
    list.append(a)
    a="/HCNetSDKCom/AnalyzeData.dll"
    list.append(a)
    a="/HCNetSDKCom/HCPreview.lib"
    list.append(a)
    a="/HCNetSDKCom/HCGeneralCfgMgr.lib"
    list.append(a)
    a="/HCNetSDKCom/HCAlarm.lib"
    list.append(a)
    for l in list:
        sql="select id from update_list where filename=%s"
        result=db.fetchonedb(sql,[l])
        if not result:
            sql="insert into update_list(filename) values(%s)"
            db.updatetodb(sql,[l])
    list=[]
    sql="select filename from update_list where closeflag=0"
    result=db.fetchalldb(sql)
    for l in result:
        list.append(l['filename'])
    #a="erm.mdb"
    #list.append(a)
    return HttpResponse(str(list))
    
#登录
def api_loginsave(request):
    username = request.GET.get('username')
    passwd = request.GET.get('pwd')
    passwdjm = request.GET.get('passwdjm')
    clientid = request.GET.get('clientid')
    xmltype = request.GET.get('xmltype')
    if passwd:
        md5pwd = hashlib.md5(passwd)
        md5pwd = md5pwd.hexdigest()[8:-8]
    else:
        if passwdjm:
            md5pwd=passwdjm[8:-8]
    if not username or not passwd:
        list={'err':'true','errtext':'用户名或密码错误','result':''}
    else:
        gmt_created=datetime.datetime.now()
        gmt_modified=datetime.datetime.now()
        token = hashlib.md5(str(passwd)+str(username)+str(gmt_modified))
        token = token.hexdigest()[8:-8]
        
        sql="select * from users where username=%s and pwd=%s"
        result=db.fetchonedb(sql,[username,md5pwd])
        if result:
            result['gmt_created']=formattime(result['gmt_created'])
            result['gmt_modified']=formattime(result['gmt_modified'])
            company_id=result['company_id']
            selfid=result['selfid']
            list={'err':'false','errtext':'','result':result}
            if not result["selfid"]:
                selfid=token
                sql="update users set selfid=%s where id=%s"
                db.updatetodb(sql,[selfid,result['id']])
            sql="update users set clientid=%s where id=%s"
            db.updatetodb(sql,[clientid,result['id']])
            #保存app登陆token
            sql="select id from app_token where token=%s"
            listd=db.fetchonedb(sql,[token])
            if not listd:
                sqlb="select id from app_token where selfid=%s"
                listb=db.fetchonedb(sqlb,[selfid])
                if not listb:
                    sqlm="insert into app_token(selfid,company_id,token,gmt_created,gmt_modified) values(%s,%s,%s,%s,%s)"
                    db.updatetodb(sqlm,[selfid,company_id,token,gmt_created,gmt_created])
                else:
                    sqlm="update app_token set company_id=%s,token=%s,gmt_modified=%s where selfid=%s"
                    db.updatetodb(sqlm,[company_id,token,gmt_modified,selfid])
            else:
                sqlm="update app_token set selfid=%s,company_id=%s,gmt_modified=%s where token=%s"
                db.updatetodb(sqlm,[selfid,company_id,gmt_modified,token])
        else:
            list={'err':'true','errtext':'用户名或密码错误','result':''}
    if xmltype:
        xml=dict2xml(list,wrap='xml')
        return HttpResponse(xml)
    else:
        return HttpResponse(simplejson.dumps(list, ensure_ascii=False))
#查询供应商
def api_searchsuppliers(request):
    iccode=request.GET.get("iccode")
    pname=request.GET.get("pname")
    group_id=request.GET.get("group_id")
    xmltype=request.GET.get("xmltype")
    list={'err':'true','list':''}
    if iccode:
        sql="select * from suppliers where iccode=%s and group_id=%s limit 0,20"
        result=db.fetchalldb(sql,[iccode,group_id])
        if result:
            for dic in result:
                dic['gmt_created']=formattime(dic['gmt_created'])
                dic['gmt_modified']=formattime(dic['gmt_modified'])
            list['err']='false'
            list['list']=result
    if pname:
        sql="select * from suppliers where name like %s  and group_id=%s limit 0,20"
        result=db.fetchalldb(sql,['%'+pname+'%',group_id])
        if result:
            for dic in result:
                dic['gmt_created']=formattime(dic['gmt_created'])
                dic['gmt_modified']=formattime(dic['gmt_modified'])
            list['err']='false'
            list['list']=result
    if xmltype:
        xml=dict2xml(list,wrap='xml')
        return HttpResponse(xml)
    else:
        return HttpResponse(simplejson.dumps(list, ensure_ascii=False))
def imgupload(request):
    return render_to_response('imgload.html',locals())
#----图片上传
def api_upload(request):
    xmltype=request.GET.get("xmltype")
    user_selfid=request.GET.get("user_selfid")
    company_id=request.GET.get("company_id")
    storage_selfid=request.GET.get("storage_selfid")
    timepath=time.strftime('%Y-%m-%d',time.localtime(time.time()))
    gmt_created=datetime.datetime.now()
    nowtime=int(time.time())
    list={}
    if request.FILES:
        file = request.FILES['file']
        tempim = StringIO.StringIO()
        mstream = StringIO.StringIO(file.read())
        im = Image.open(mstream)
        rheight=500
        rwidth=500
        
        pwidth=im.size[0]
        pheight=im.size[1]
        
        rate = int(pwidth/pheight)
        if rate==0:
            rate=1
        nwidth=200
        nheight=200
        if (pwidth>rwidth):
            nwidth=rwidth
            nheight=nwidth /rate
        else:
            nwidth=pwidth
            nheight=pheight
        
        if (pheight>rheight):
            nheight=rheight
            nwidth=rheight*rate
        else:
            nwidth=pwidth
            nheight=pheight
        im.thumbnail((nwidth,nheight),Image.ANTIALIAS)
        tmp = random.randint(100, 999)
        newpath=pyuploadpath+timepath
        #imgpath=newpath+"/"+str(nowtime)+str(tmp)+"."+im.format
        imgname=str(request.FILES['file'])
        imgpath=newpath+"/"+imgname
        if not os.path.isdir(newpath):
            os.makedirs(newpath)

#       im.save(imgpath,im.format,quality = 100)

        des_origin_f = open(imgpath,"w")
        
        for chunk in file.chunks():  
            des_origin_f.write(chunk)  
        des_origin_f.close()
        mstream.closed
        tempim.closed
        
        #-车牌识别
        #f=open(imgpath,'rb') #二进制方式打开图文件
        #ls_f=base64.b64encode(f.read()) #读取文件内容，转换为base64编码
        #f.close()
        #return HttpResponse(api_chepaishow(ls_f))
        
        picurl=imgpath.replace(pyuploadpath,'')
        pic_url=pyimgurl+picurl
        sql="insert into storage_pic(company_id,storage_selfid,pic,gmt_created,gmt_modified) values(%s,%s,%s,%s,%s)"
        db.updatetodb(sql,[company_id,storage_selfid,pic_url,gmt_created,gmt_created])
    if xmltype:
        xml=dict2xml(list,wrap='xml')
        return HttpResponse(xml)
    else:
        return HttpResponse(simplejson.dumps(list, ensure_ascii=False))
    
#车牌识别

def api_chepaishow(imgcode):
    host = 'http://ocrcp.market.alicloudapi.com'
    path = '/rest/160601/ocr/ocr_vehicle_plate.json'
    method = 'POST'
    appcode = '43bd55f8dd8f4985aec5ef3d2019f9bc'
    url = host + path
    bodys={
        "inputs": [
        {
            "image": {
                "dataType": 50,
                "dataValue": imgcode
            },
            "configure": {
                "dataType": 50,
                "dataValue": "{\"multi_crop\":false}"
            }
        }]
    }
    headers={'Authorization':'APPCODE ' + appcode,'content-type': 'application/json; charset=UTF-8'}
    r = requests.post(url, data=json.dumps(bodys), headers=headers)
    return r.text

#用户权限
def api_getauth(request):
    xmltype=request.GET.get("xmltype")
    user_selfid=request.GET.get("user_selfid")
    company_id=request.GET.get("company_id")
    sql="select utype from users where selfid=%s"
    result=db.fetchonedb(sql,[user_selfid])
    list={}
    if result:
        list['utype']=result['utype']
    sql="select isprice,isscore from company where id=%s"
    result=db.fetchonedb(sql,[company_id])
    if result:
        list['isprice']=result['isprice']
        list['isscore']=result['isscore']
    else:
        list['isprice']=0
        list['isscore']=0
    if xmltype:
        xml=dict2xml(list,wrap='xml')
        return HttpResponse(xml)
    else:
        return HttpResponse(simplejson.dumps(list, ensure_ascii=False))
def getversion(request):
    xmltype=request.GET.get("xmltype")
    list={'version':'1.0.7'}
    if xmltype:
        xml=dict2xml(list,wrap='xml')
        return HttpResponse(xml)
    else:
        return HttpResponse(simplejson.dumps(list, ensure_ascii=False))
#更新数据
def api_datatable_update(request):
    maxid=request.GET.get("maxid")
    datatable=request.GET.get("datatable")
    company_id=request.GET.get("company_id")
    xmltype=request.GET.get("xmltype")
    list={'err':'true','list':''}
    if datatable:
        if maxid=="0" or not maxid:
            maxdate='1970-1-1'
        else:
            maxdate=int_to_strall(int(maxid))
        if datatable=="category_products":
            tablename="category_products"
        if datatable=="products":
            tablename="products"
        if datatable=="suppliers":
            tablename="suppliers"
        if datatable=="users":
            tablename="users"
        if datatable=="storage":
            tablename="storage"
        if datatable=="cars":
            tablename="cars"
        
        
        if datatable=="company":
            tablename="company"
            sql="select * from "+tablename+" where id=%s"
            result=db.fetchalldb(sql,[company_id])
        elif datatable=="grouplist":
            tablename="grouplist"
            sql="select * from "+tablename+" where id=%s"
            result=db.fetchalldb(sql,[company_id])
        else:
            if datatable=="storage":
                sql="select * from storage where gmt_modified>%s and company_id=%s order by gmt_modified asc"
            else:
                sql="select * from "+tablename+" where gmt_modified>%s and company_id=%s order by gmt_modified asc"
            result=db.fetchalldb(sql,[maxdate,company_id])
        
        if result:
            for dic in result:
                dic['gmt_created']=formattime(dic['gmt_created'])
                dic['gmt_modified']=formattime(dic['gmt_modified'])
                if datatable=="storage":
                    dic['price_time']=formattime(dic['price_time'])
                    dic['out_time']=formattime(dic['out_time'])
                    dic['pay_time']=formattime(dic['pay_time'])
            list['err']='false'
            list['list']=result
        #return HttpResponse(sql)
    if xmltype:
        xml=dict2xml(list,wrap='xml')
        return HttpResponse(xml)
    else:
        return HttpResponse(simplejson.dumps(list, ensure_ascii=False))

def api_getstoragedate(request):
    company_id=request.GET.get("company_id")
    sql="select max(gmt_modified) as gmt_modified from storage where company_id=%s"
    result=db.fetchonedb(sql,[company_id])
    if result:
        if result['gmt_modified']:
            return HttpResponse(formattime(result['gmt_modified']))
        else:
            return HttpResponse("0")
    else:
        return HttpResponse("0")
def api_getproductsdate(request):
    company_id=request.GET.get("company_id")
    sql="select max(gmt_modified) as gmt_modified from products where company_id=%s"
    result=db.fetchonedb(sql,[company_id])
    if result:
        if result['gmt_modified']:
            return HttpResponse(formattime(result['gmt_modified']))
        else:
            return HttpResponse("0")
    else:
        return HttpResponse("0")
    #return HttpResponse(simplejson.dumps(list, ensure_ascii=False))
def api_getsuppliersdate(request):
    company_id=request.GET.get("company_id")
    sql="select max(gmt_modified) as gmt_modified from suppliers where company_id=%s"
    result=db.fetchonedb(sql,[company_id])
    if result:
        if result['gmt_modified']:
            return HttpResponse(formattime(result['gmt_modified']))
        else:
            return HttpResponse("0")
    else:
        return HttpResponse("0")
    
#----更新供应商
def api_updatesuppliers(request):
    supplierlist=request.POST.get("supplierlist")
    if not supplierlist:
        supplierlist=request.GET.get("supplierlist")
    if supplierlist:
        supparr1=supplierlist.split("$")
        for list in supparr1:
            a=list.split("|")
            if len(a)>12:
                selfid=a[0]
                ctype=a[1]
                iccode=a[2]
                group_id=a[3]
                company_id=a[4]
                name=a[5]
                htype=a[6]
                contact=a[7]
                mobile=a[8]
                pwd=a[9]
                address=a[10]
                bz=a[11]
                gmt_created=a[12]
                gmt_modified=a[13]
                isdel=a[14]
                scode=a[15]
                sql="select id from suppliers where selfid=%s"
                result=db.fetchonedb(sql,[selfid])
                if not result:
                    sql="insert into suppliers(selfid,ctype,iccode,group_id,company_id,name,htype,contact,mobile,pwd,address,bz,gmt_created,gmt_modified,isdel,scode) values"
                    sql+="(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
                    db.updatetodb(sql,[selfid,ctype,iccode,group_id,company_id,name,htype,contact,mobile,pwd,address,bz,gmt_created,gmt_modified,isdel,scode])
                else:
                    sql="update suppliers set ctype=%s,iccode=%s,name=%s,htype=%s,contact=%s,mobile=%s,pwd=%s,address=%s,bz=%s,gmt_modified=%s,isdel=%s,scode=%s where selfid=%s"
                    db.updatetodb(sql,[ctype,iccode,name,htype,contact,mobile,pwd,address,bz,gmt_modified,isdel,scode,selfid])
    return HttpResponse("0")
#----更新产品
def api_updateproducts(request):
    productslist=request.POST.get("productslist")
    if not productslist:
        productslist=request.GET.get("productslist")
    if productslist:
        productsarr1=productslist.split("$")
        for list in productsarr1:
            a=list.split("|")
            if len(a)>8:
                selfid=a[0]
                group_id=a[1]
                company_id=a[2]
                name=a[3]
                spec=a[4]
                unit=a[5]
                gmt_created=a[6]
                gmt_modified=a[7]
                isdel=a[8]
                    
                sql="select id from products where selfid=%s"
                result=db.fetchonedb(sql,[selfid])
                if not result:
                    sql="insert into products(selfid,group_id,company_id,name,spec,unit,gmt_created,gmt_modified,isdel) values"
                    sql+="(%s,%s,%s,%s,%s,%s,%s,%s,%s)"
                    db.updatetodb(sql,[selfid,group_id,company_id,name,spec,unit,gmt_created,gmt_modified,isdel])
                else:
                    sql="update products set name=%s,spec=%s,unit=%s,gmt_modified=%s,isdel=%s where selfid=%s"
                    db.updatetodb(sql,[name,spec,unit,gmt_modified,isdel,selfid])
    return HttpResponse("0")
#----更新库存信息
def api_updatestorage(request):
    storelist=request.POST.get("storelist")
    if not storelist:
        storelist=request.GET.get("storelist")
    #return HttpResponse(storelist)
    if not storelist:
        return HttpResponse("0")
    if storelist:
        try:
            storelistarr1=storelist.split("$")
            for list in storelistarr1:
                a=list.split("|")
                if len(a)>21:
                    selfid=a[0]
                    #return HttpResponse(a[1])
                    group_id=a[1]
                    company_id=a[2]
                    code=a[3]
                    products_selfid=a[4]
                    suppliers_selfid=a[5]
                    price=a[6]
                    gw=a[7]
                    nw=a[8]
                    tare=a[9]
                    tare_check=a[10]
                    total=a[11]
                    status=a[12]
                    price_users_selfid=a[13]
                    price_time=a[14]
                    out_time=a[15]
                    ispay=a[16]
                    scorecheck=a[17]
                    pay_time=a[18]
                    pay_users_selfid=a[19]
                    gmt_created=a[20]
                    gmt_modified=a[21]
                    gmt_modified=datetime.datetime.now()
                    eqtype=""
                    isdel=""
                    licence=""
                    stype=""
                    bz=""
                    if len(a)>21:
                        eqtype=a[22]
                        isdel=a[23]
                        licence=a[24]
                        stype=a[25]
                        bz=a[26]
                    sql="select id from storage where selfid=%s"
                    result=db.fetchonedb(sql,[selfid])
                    if not result:
                        sql="insert into storage(selfid,group_id,company_id,code,products_selfid,suppliers_selfid,price,gw,nw,tare,tare_check,total,status,price_users_selfid,price_time,out_time,ispay,scorecheck,pay_time,pay_users_selfid,gmt_created,gmt_modified,eqtype,isdel,licence,stype,bz) values"
                        sql+="(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
                        db.updatetodb(sql,[selfid,group_id,company_id,code,products_selfid,suppliers_selfid,price,gw,nw,tare,tare_check,total,status,price_users_selfid,price_time,out_time,ispay,scorecheck,pay_time,pay_users_selfid,gmt_created,gmt_modified,eqtype,isdel,licence,stype,bz])
                        weixintixin(selfid)
                    else:
                        sql="update storage set products_selfid=%s,suppliers_selfid=%s,price=%s,gw=%s,nw=%s,tare=%s,tare_check=%s,total=%s,status=%s,price_users_selfid=%s,price_time=%s,out_time=%s,ispay=%s,scorecheck=%s,pay_time=%s,pay_users_selfid=%s,gmt_modified=%s,eqtype=%s,isdel=%s,licence=%s,stype=%s,bz=%s where selfid=%s"
                        db.updatetodb(sql,[products_selfid,suppliers_selfid,price,gw,nw,tare,tare_check,total,status,price_users_selfid,price_time,out_time,ispay,scorecheck,pay_time,pay_users_selfid,gmt_modified,eqtype,isdel,licence,stype,bz,selfid])
            company_id=request.POST.get("company_id")
            sql="select max(gmt_modified) as gmt_modified from storage where company_id=%s"
            result=db.fetchonedb(sql,[company_id])
            if result:
                if result['gmt_modified']:
                    return HttpResponse(formattime(result['gmt_modified']))
            return HttpResponse("0")
        except Exception , e:
            return HttpResponse("0")
    return HttpResponse("1")
#----入库微信提醒
    
#微信
def api_weixinget(request):
    #地磅微信
    token = "dibang123weixin"
    params = request.GET
    args = [token, params['timestamp'], params['nonce']]
    args.sort()
    if hashlib.sha1("".join(args)).hexdigest() == params['signature']:
        if params.has_key('echostr'):
            return HttpResponse(params['echostr'])
        else:
            if request.body:
                xml = ET.fromstring(request.body)
                fromUserName = xml.find("ToUserName").text
                toUserName = xml.find("FromUserName").text
                MsgType = xml.find("MsgType").text
                Event1=None
                content=None
                EventKey=""
                if (MsgType=="event"):
                    Event1 = xml.find("Event").text
                    EventKey = xml.find("EventKey").text
                if (MsgType=="text"):
                    content = xml.find("Content").text
                if (MsgType=="image"):
                    PicUrl = xml.find("PicUrl").text
                if EventKey==None:
                    keyw=Event1
                else:
                    keyw=EventKey
                #记录日志
                
                if (Event1 == "subscribe" or Event1 == "SCAN"):
                    try:
                        if EventKey:
                            title=""
                            EventKey=EventKey.lower().replace("qrscene_", "")
                            if EventKey:
                                qrcode=EventKey
                                gmt_created=datetime.datetime.now()
                                sql="select id from weixin where company_id=%s and weixinid=%s"
                                result=db.fetchonedb(sql,[qrcode,toUserName])
                                if not result:
                                    sql="insert into weixin(company_id,weixinid,gmt_created) values(%s,%s,%s)"
                                    db.updatetodb(sql,[qrcode,toUserName,gmt_created])
                    except Exception , e:
                        err=1
                        sql="insert into err_log (content) values(%s)"
                        db.updatetodb(sql,[e])
                    title="您好！感谢关注再生资源智能系统"
                    xml=backxml(xmltype=2,fromUserName=toUserName,toUserName=fromUserName,title=title)
                    return HttpResponse(xml)
                else:
                    title=content
                    
                if (content==None  and EventKey=='qiandao'):
                    tpurl="http://m.zz91.com/wechat/auth_login.html?tourl=/zsh/index.html?clientid="+str(toUserName)+""
                    titlelist=[{'title':'2017废纸产业发展论坛现场签到','Description':'点此签到','PicUrl':'http://m.zz91.com/zt/feizhiluntanH5/images/weixin_qiandao.jpg','Url':tpurl}]
                    ArticleCount=len(titlelist)
                    xml=backxml(xmltype=3,fromUserName=toUserName,toUserName=fromUserName,ArticleCount=ArticleCount,titlelist=titlelist)
                    return HttpResponse(xml)
                else:
                    return HttpResponse("Invalid Request")
    else:
        return HttpResponse("Invalid Request")


def category_save(request):
    username=request.session.get('username',default=None)
    company_id=request.session.get('company_id',default=None)
    group_id=request.session.get('group_id',default=None)
    if not username:
        return HttpResponseRedirect("login.html")
    id=request.POST.get('id')
    sub_selfid=request.POST.get('sub_selfid')
    if not sub_selfid:
        sub_selfid=0
    name=request.POST.get('name')
    gmt_created=datetime.datetime.now()
    gmt_modified=datetime.datetime.now()
    if id:
        sql='update category_products set name=%s,gmt_modified=%s where id=%s'
        result=db.updatetodb(sql,[name,gmt_modified,id])
    else:
        selfid=str(time.time())+str(company_id)+str(random.randint(100, 999))
        md5selfid = hashlib.md5(selfid)
        selfid = md5selfid.hexdigest()[8:-8]
        sql='insert into category_products(selfid,sub_selfid,group_id,company_id,name,gmt_created,gmt_modified) values(%s,%s,%s,%s,%s,%s,%s)'
        result=db.updatetodb(sql,[selfid,sub_selfid,group_id,company_id,name,gmt_created,gmt_modified])
    ret={"err":"false"}
    return HttpResponse(simplejson.dumps(ret, ensure_ascii=False))

def category_del(request):
    id=request.POST.get('id')
    sql='update category_products set isdel=1 where id=%s'
    db.updatetodb(sql,[id])
    ret={"err":"false"}
    return HttpResponse(simplejson.dumps(ret, ensure_ascii=False))